package socketmvc.core.util.xpath;

import java.util.Arrays;

/**
 * 正则通配符实现
 * @author xueyanjun
 */
public class RegexPathMatcher extends AbstractPathMatcher{
    private static final String PATTERN_LINE_START = "^" ;

    private static final String PATTERN_LINE_END = "$" ;

    private static final char[] META_CHARACTERS = {'$', '^', '[', ']', '(', ')', '{', '}', '|', '+', '.', '\\'};

    /**
     * 字符串与通配符进行比较
     *
     * @param path     路径字符串
     * @param wildcard 匹配符/通配符
     * @return 匹配结果 true 代表匹配成功
     */
    @Override
    protected boolean doMatch(String path, String wildcard) {
        return path.matches(convertToRegexPattern(wildcard));
    }

    /**
     * 转换通配符
     * @param wildcard 通配符
     * @return RegexPattern 正则表达式
     */
    private String convertToRegexPattern(String wildcard) {
        StringBuilder result = new StringBuilder(PATTERN_LINE_START);
        char[] chars = wildcard.toCharArray() ;
        for (char ch : chars) {
            if (Arrays.binarySearch(META_CHARACTERS, ch)>=0) {
                result.append("\\").append(ch);
                continue ;
            }
            switch (ch) {
                case '*' -> result.append(".*");
                case '?' -> result.append(".{0,1}");
                default -> result.append(ch);
            }
        }
        result.append(PATTERN_LINE_END);
        return result.toString();
    }

    public static void main(String[] args) {
        RegexPathMatcher regexPathMatcher = new RegexPathMatcher();
        System.out.println(regexPathMatcher.match("/backend/utils/a.js","/**"));
    }
}
